import {
  Body,
  Controller,
  Get,
  Inject,
  Post,
  Res,
  Session,
} from '@nestjs/common';
import { CaptchaService } from './captcha.service';
import { Response } from 'express';
import { RedisService } from '../redis/redis.service';
import { ApiBody, ApiOperation, ApiTags } from '@nestjs/swagger';
import { Public } from '../common/isPublic';
import { Captcha } from './entities/captcha.entity';

@Controller('captcha')
@ApiTags('验证码')
export class CaptchaController {
  constructor(
    private readonly captchaService: CaptchaService,
    @Inject() private readonly redisService: RedisService,
  ) {}

  @Get()
  @Public()
  @ApiOperation({ summary: '获取验证码' })
  async createCaptcha(@Res() res: Response) {
    const captchaObj = this.captchaService.createCode();
    await this.redisService.set('captcha', captchaObj.text);
    res.type('image/svg+xml');
    res.send(captchaObj.data);
  }

  @Post()
  @Public()
  @ApiOperation({ summary: '验证' })
  async verifyCaptcha(@Body() data: Captcha) {
    const redisCaptcha = await this.redisService.get('captcha');
    const { code: captcha } = data;
    if (redisCaptcha.toLowerCase() !== captcha.toLowerCase()) {
      return {
        msg: '验证码错误',
        code: 201,
      };
    }
    await this.redisService.del('captcha');
    return {
      msg: '验证码正确',
    };
  }
}
